package com.devshephard.rpcframework.servletsync.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Slf4j
@Component
public class SyncServletImpl extends AbsSyncServletImpl {

    @Override
    public String callBack() {
        return "";
    }

    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        System.out.println(Thread.currentThread().getName() + " 执行execute方法");
    }

    public void executeChain(HttpServletRequest request, HttpServletResponse response){

        AsyncContext asyncContext = request.startAsync();

        asyncContext.addListener(new AsyncListener() {

            @Override
            public void onComplete(AsyncEvent asyncEvent) throws IOException {
                new Thread(()->{
                    afterExecute();
                }).start();
            }
            @Override
            public void onTimeout(AsyncEvent asyncEvent) throws IOException {
                log.info(new Date() + Thread.currentThread().getName() +"response线程处理超时");
            }
            @Override
            public void onError(AsyncEvent asyncEvent) throws IOException {
                log.info(new Date() + Thread.currentThread().getName() +"response线程处理异常");
            }
            @Override
            public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
                log.info(new Date() + Thread.currentThread().getName() +"response线程开始处理事件");
            }
        });


        Runnable runnable = () -> {
            try {
                this.execute(request,response);
                asyncContext.getResponse().getWriter().write(this.callBack());
            } catch (IOException e) {
                e.printStackTrace();
            }

            asyncContext.complete();

        };
        new Thread(runnable).start();



    }

    public void afterExecute() {

    }


}
